<?php

namespace App\Http\Middleware;

use App\Http\Common\Lib\Common;
use App\Models\AdminUser;
use Closure;

class AdminAuth
{
    /**
     * 后台权限检测
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = $request->session()->get('adminUser',null);
        if(!$user){
            return redirect('admin/login');
        }
        if($user->id != 1){
            $path = $request->path();
            $method = $request->getMethod();
            $menus = $this->myMenus();
            if(in_array($path,$menus['free']) || in_array($path,$menus['any'])){
                return $next($request);
            }
            $flag = false;
            switch (strtolower($method)){
                case 'get':
                    if(in_array($path,$menus['get'])){
                        $flag = true;
                    }
                    break;
                case 'post':
                    if(in_array($path,$menus['post'])){
                        $flag = true;
                    }
                    break;
            }
            if(!$flag){
               if($request->ajax()){
                   return response()->json(Common::dataFormat(config('statusInfo.status.noAuth'),config('statusInfo.msg.noAuth')));
               }else{
                   return view('admin.noAuth');
               }
            }
        }
        return $next($request);
    }

    /**
     * 从session中获取url
     * @return array
     */
    public function myMenus(){
        $data = \request()->session()->get('adminMenus',null);
        $now = time();
        if($data && $data['expire_in'] > $now){
            return $data['menus'];
        }
        $menus = $this->getMenus();
        $data = [
            'menus'=>$menus,
            'expire_in'=>$now + 600,
        ];
        \request()->session()->put('adminMenus',$data);
        return $menus;
    }

    /**
     * 获取url
     * @return array
     */
    public function getMenus(){
        $userModel = new AdminUser();
        $user = \request()->session()->get('adminUser',null);
        $free = $userModel->getUserUrls($user->id,0,false);
        $any = $userModel->getUserUrls($user->id,0);
        $get = $userModel->getUserUrls($user->id,1);
        $post = $userModel->getUserUrls($user->id,2);
        return [
            'free'=>$free,
            'any'=>$any,
            'get'=>$get,
            'post'=>$post,
        ];
    }
}
